package com.luom.fsp.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.luom.fsp.common.ErrorCode;
import com.luom.fsp.constant.CommonConstant;
import com.luom.fsp.exception.ThrowUtils;
import com.luom.fsp.mapper.CartMapper;
import com.luom.fsp.model.dto.cart.CartQueryRequest;
import com.luom.fsp.model.entity.Cart;
import com.luom.fsp.model.entity.Product;
import com.luom.fsp.model.entity.ProductSKU;
import com.luom.fsp.model.entity.User;
import com.luom.fsp.model.vo.CartVO;
import com.luom.fsp.model.vo.ProductMainVO;
import com.luom.fsp.model.vo.ProductSKUVO;
import com.luom.fsp.model.vo.UserVO;
import com.luom.fsp.service.CartService;
import com.luom.fsp.service.ProductSKUService;
import com.luom.fsp.service.ProductService;
import com.luom.fsp.service.UserService;
import com.luom.fsp.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 购物车服务实现
 *
*/
@Service
@Slf4j
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements CartService {

    @Resource
    private UserService userService;

    @Resource
    private ProductSKUService productSKUService;

    @Resource
    private ProductService productService;

    /**
     * 校验数据
     *
     * @param cart
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validCart(Cart cart, boolean add) {
        ThrowUtils.throwIf(cart == null, ErrorCode.PARAMS_ERROR);

        Long id = cart.getId();
        Long skuId = cart.getSkuId();
        Integer quantity = cart.getQuantity();

        // 创建数据时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(ObjectUtils.isEmpty(skuId), ErrorCode.PARAMS_ERROR, "商品不能为空");
            ThrowUtils.throwIf(ObjectUtils.isEmpty(quantity), ErrorCode.PARAMS_ERROR, "商品数量不能为空");
        }
    }

    /**
     * 获取查询条件
     *
     * @param cartQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Cart> getQueryWrapper(CartQueryRequest cartQueryRequest) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        if (cartQueryRequest == null) {
            return queryWrapper;
        }
        Long userId = cartQueryRequest.getUserId();
        String sortField = cartQueryRequest.getSortField();
        String sortOrder = cartQueryRequest.getSortOrder();
        // 精确查询
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取购物车封装
     *
     * @param cart
     * @param request
     * @return
     */
    @Override
    public CartVO getCartVO(Cart cart, HttpServletRequest request) {
        // 对象转封装类
        CartVO cartVO = CartVO.objToVo(cart);

        // 获取商品规格
        cartVO.setProductSKUVO(ProductSKUVO.objToVo(productSKUService.getById(cart.getSkuId())));

        // 获取商品
        cartVO.setProduct(ProductMainVO.objToVo(productService.getById(cartVO.getProductSKUVO().getProductId())));

        return cartVO;
    }

    /**
     * 分页获取购物车封装
     *
     * @param cartPage
     * @param request
     * @return
     */
    @Override
    public Page<CartVO> getCartVOPage(Page<Cart> cartPage, HttpServletRequest request) {
        List<Cart> cartList = cartPage.getRecords();
        Page<CartVO> cartVOPage = new Page<>(cartPage.getCurrent(), cartPage.getSize(), cartPage.getTotal());

        if (CollUtil.isEmpty(cartList)) {
            return cartVOPage;
        }

        // **提取所有 skuId**
        List<Long> skuIds = cartList.stream().map(Cart::getSkuId).collect(Collectors.toList());

        // **批量查询 SKU 信息**
        Map<Long, ProductSKUVO> skuMap = productSKUService.list(new QueryWrapper<ProductSKU>().in("id", skuIds))
                .stream().collect(Collectors.toMap(ProductSKU::getId, ProductSKUVO::objToVo));

        // **提取所有商品 productId**
        List<Long> productIds = skuMap.values().stream().map(ProductSKUVO::getProductId).distinct().collect(Collectors.toList());

        // **批量查询商品信息**
        Map<Long, ProductMainVO> productMap = productService.list(new QueryWrapper<Product>().in("id", productIds))
                .stream().collect(Collectors.toMap(Product::getId, ProductMainVO::objToVo));

        // **填充数据**
        List<CartVO> cartVOList = cartList.stream().map(cart -> {
            CartVO cartVO = CartVO.objToVo(cart);

            // 填充 SKU 信息
            ProductSKUVO skuVO = skuMap.get(cart.getSkuId());
            cartVO.setProductSKUVO(skuVO);

            // 填充商品信息
            if (skuVO != null) {
                cartVO.setProduct(productMap.get(skuVO.getProductId()));
            }

            return cartVO;
        }).collect(Collectors.toList());

        cartVOPage.setRecords(cartVOList);
        return cartVOPage;
    }


}
